const { Op } = require("sequelize")

const { getUserByAccount } = require('../service/user.service')

const {
    createChuangxin,
    editChuangxin,
    createXueye,
    editXueye,
    createSixiang,
    editSixiang,
    createWenti,
    editWenti,
    getChuangxinList,
    getXueyeList,
    getSixiangList,
    getWentiList,
    modifyScoreByActId
} = require('../service/actScore.service')

const {
    getACtDetailById,
    modifyByActId
} = require('../service/activity.service')

const {
    addLocation,
    getActLoaction,
    modifyLocationByActId
} = require('../service/actLocation.service')

const {
    getUserInfo
} = require('../service/user.service')

const { getEntryInfo, modifyEntry, approvalEntry } = require('../service/entryDocuments.service')

const { formatDate } = require('../utils/formatData')

const { getActSignScoreListByActId } = require('../service/actSignScore.service')

class actScoreController {
    /**
      * 活动加分
    */
    async actBouns (ctx, next) {
        const { actId, userAccount, signTime } = ctx.request.body
        const scoreSignList = ctx.state.scoreSignList
        const isFirstSign = ctx.state.isFirstSign // true 为签到 false为签退
        let year = ''

        if (signTime) {
            year = signTime.split(' ')[0]
        } else {
            const res = await getACtDetailById(actId)
            year = res.start_time.split(' ')[0]
        }
        let res = {}
        let isSign = false
        for (let item of scoreSignList) {
            switch (item.score_type) {
                case 0:
                    // 0 为创新分
                    const serachChuangxinRes = await getChuangxinList({ act_id: actId, user_account: userAccount })
                    if (serachChuangxinRes.length === 0) {
                        // 签到
                        res = await createChuangxin({ act_id: actId, user_account: userAccount, score: item.score, year })
                    } else {
                        // 签退
                        const isSignOutRes = await getChuangxinList({ act_id: actId, user_account: userAccount, score_approval_status: 3 })
                        if (isSignOutRes.length === 0) {
                            res = await editChuangxin({ score_approval_status: 3 }, actId, userAccount)
                        } else {
                            isSign = true
                        }

                    }
                    break
                case 1:
                    // 1 为学业分
                    const serachXueyeRes = await getXueyeList({ act_id: actId, user_account: userAccount })
                    if (serachXueyeRes.length === 0) {
                        // 签到
                        res = await createXueye({ act_id: actId, user_account: userAccount, score: item.score, year })
                    } else {
                        // 签退
                        const isSignOutRes = await getXueyeList({ act_id: actId, user_account: userAccount, score_approval_status: 3 })
                        if (isSignOutRes.length === 0) {
                            res = await editXueye({ score_approval_status: 3 }, actId, userAccount)
                        } else {
                            isSign = true
                        }
                    }
                    break
                case 2:
                    // 2 为思想分
                    const serachSixiangRes = await getSixiangList({ act_id: actId, user_account: userAccount })
                    if (serachSixiangRes.length === 0) {
                        // 签到
                        res = await createSixiang({ act_id: actId, user_account: userAccount, score: item.score, year })
                    } else {
                        // 签退
                        const isSignOutRes = await getSixiangList({ act_id: actId, user_account: userAccount })
                        if (isSignOutRes.length === 0) {
                            res = await editSixiang({ score_approval_status: 3 }, actId, userAccount)
                        } else {
                            isSign = true
                        }
                    }
                    break
                case 3:
                    // 3 为文体分
                    const serachWentiRes = await getWentiList({ act_id: actId, user_account: userAccount })
                    if (serachWentiRes.length === 0) {
                        // 签到
                        res = await createWenti({ act_id: actId, user_account: userAccount, score: item.score, year })
                    } else {
                        // 签退
                        const isSignOutRes = await getWentiList({ act_id: actId, user_account: userAccount })
                        if (isSignOutRes.length === 0) {
                            res = await editWenti({ score_approval_status: 3 }, actId, userAccount)
                        } else {
                            isSign = true
                        }
                    }
                    break
            }
        }

        if (res.errorFlag) {
            console.error('新增失败，数据库新增数据错误', res.message)
            ctx.status = 500
        } else {
            if (isSign) {
                ctx.status = 200
                ctx.body = {
                    hasOk: false,
                    code: 20000,
                    message: '你已完成签到签退！',
                    data: {}
                }
            } else if (!isFirstSign) {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '签退成功',
                    data: {}
                }
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '签到成功',
                    data: {}
                }
            }
        }
    }


    /**
     * 获取某活动加分文件
     */
    async getActScoreFile (ctx, next) {
        const { actId, scoreApprovalStatus } = ctx.query
        let tempList = []
        const chuangxinRes = await getChuangxinList({ act_id: actId })
        tempList.push(...chuangxinRes)
        const xueyeRes = await getXueyeList({ act_id: actId })
        tempList.push(...xueyeRes)
        const sixiangRes = await getSixiangList({ act_id: actId })
        tempList.push(...sixiangRes)
        const wentiRes = await getWentiList({ act_id: actId })
        tempList.push(...wentiRes)

        let resList = []
        for (let item of tempList) {
            let tempObj = {}
            const userRes = await getUserInfo({ user_account: item.user_account })
            const userDataValues = userRes[0].dataValues
            tempObj.userName = userDataValues.user_name
            tempObj.actId = item.act_id
            tempObj.scoreApprovalStatus = item.score_approval_status
            tempObj.score = item.score
            tempObj.year = item.year
            tempObj.scoreType = item.score_type
            let scoreApprovalStatusDesc = ''
            switch (item.score_approval_status) {
                case 0:
                    scoreApprovalStatusDesc = '未签退'
                    break
                case 1:
                    scoreApprovalStatusDesc = '已审批'
                    break
                case 3:
                    scoreApprovalStatusDesc = '未审批'
            }
            tempObj.scoreApprovalStatusDesc = scoreApprovalStatusDesc
            let scoreTypeStatus = ''
            switch (item.score_type) {
                case 0:
                    scoreTypeStatus = '创新分'
                    // 0 为创新分
                    break
                case 1:
                    // 1 为学业分
                    scoreTypeStatus = '学业分'
                    break
                case 2:
                    // 2 为思想分
                    scoreTypeStatus = '思想分'
                    break
                case 3:
                    // 3 为文体分
                    scoreTypeStatus = '文体分'
                    break
            }
            tempObj.scoreTypeStatus = scoreTypeStatus
            resList.sort((a, b) => a.scoreType - b.scoreType)
            resList.push(tempObj)
        }
        ctx.status = 200
        ctx.status = 200
        ctx.body = {
            hasOk: true,
            code: 20000,
            message: '加分文件已获取',
            data: resList
        }
    }

    async getChuangxinByAccount (ctx, next) {
        const { userAccount: user_account, getStatus, scoreApprovalStatus: score_approval_status, startYear, endYear } = ctx.query
        const whereOpt = {}
        user_account && Object.assign(whereOpt, { user_account })
        score_approval_status && Object.assign(whereOpt, { score_approval_status })
        if (startYear && endYear) {
            whereOpt.year = { [Op.between]: [startYear, endYear] }
        }
        const chuangxinRes = await getChuangxinList(whereOpt)
        if (getStatus === '1') {
            // 获取加分列表
            let resList = []
            for (let item of chuangxinRes) {
                let tempObj = {}
                tempObj.actId = item.act_id
                const res = await getACtDetailById(item.act_id)
                tempObj.actTitle = res.act_title
                tempObj.userAccount = item.user_account
                tempObj.year = item.year
                tempObj.score = item.score
                tempObj.scoreType = item.score_type
                tempObj.scoreTypeStatus = '创新分'

                resList.push(tempObj)
            }
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '创新分已获取',
                data: resList
            }
        } else {
            // 获取分数
            let chuangxinTotalScore = 0.0
            chuangxinRes.forEach(item => {
                chuangxinTotalScore += item.score
            })
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '创新分已获取',
                data: { chuangxinTotalScore }
            }
        }

    }

    async getXueyeByAccount (ctx, next) {
        const { userAccount: user_account, getStatus, scoreApprovalStatus: score_approval_status, startYear, endYear } = ctx.query
        const whereOpt = {}
        user_account && Object.assign(whereOpt, { user_account })
        score_approval_status && Object.assign(whereOpt, { score_approval_status })
        if (startYear && endYear) {
            whereOpt.year = { [Op.between]: [startYear, endYear] }
        }
        const xueyeRes = await getXueyeList(whereOpt)
        if (getStatus === '1') {
            // 获取加分列表
            let resList = []
            for (let item of xueyeRes) {
                let tempObj = {}
                tempObj.actId = item.act_id
                const res = await getACtDetailById(item.act_id)
                tempObj.actTitle = res.act_title
                tempObj.userAccount = item.user_account
                tempObj.year = item.year
                tempObj.score = item.score
                tempObj.scoreType = item.score_type
                tempObj.scoreTypeStatus = '学业分'

                resList.push(tempObj)
            }
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '学业分已获取',
                data: resList
            }
        } else {
            // 获取分数
            let xueyeTotalScore = 0.0
            xueyeRes.forEach(item => {
                xueyeTotalScore += item.score
            })
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '学业分已获取',
                data: { xueyeTotalScore }
            }
        }
    }

    async getSixiangByAccount (ctx, next) {
        const { userAccount: user_account, getStatus, scoreApprovalStatus: score_approval_status, startYear, endYear } = ctx.query
        const whereOpt = {}
        user_account && Object.assign(whereOpt, { user_account })
        score_approval_status && Object.assign(whereOpt, { score_approval_status })
        if (startYear && endYear) {
            whereOpt.year = { [Op.between]: [startYear, endYear] }
        }

        const sixiangRes = await getSixiangList(whereOpt)
        if (getStatus === '1') {
            // 获取加分列表
            let resList = []
            for (let item of sixiangRes) {
                let tempObj = {}
                tempObj.actId = item.act_id
                const res = await getACtDetailById(item.act_id)
                tempObj.actTitle = res.act_title
                tempObj.userAccount = item.user_account
                tempObj.year = item.year
                tempObj.score = item.score
                tempObj.scoreType = item.score_type
                tempObj.scoreTypeStatus = '思想分'

                resList.push(tempObj)
            }
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '思想分已获取',
                data: resList
            }
        } else {
            // 获取分数
            let sixiangTotalScore = 0.0
            sixiangRes.forEach(item => {
                sixiangTotalScore += item.score
            })
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '思想分已获取',
                data: { sixiangTotalScore }
            }

        }


    }

    async getWentiByAccount (ctx, next) {
        const { userAccount: user_account, getStatus, scoreApprovalStatus: score_approval_status, startYear, endYear } = ctx.query
        const whereOpt = {}
        user_account && Object.assign(whereOpt, { user_account })
        score_approval_status && Object.assign(whereOpt, { score_approval_status })
        if (startYear && endYear) {
            whereOpt.year = { [Op.between]: [startYear, endYear] }
        }

        const wentiRes = await getWentiList(whereOpt)
        if (getStatus === '1') {
            // 获取加分列表
            let resList = []
            for (let item of wentiRes) {
                let tempObj = {}
                tempObj.actId = item.act_id
                const res = await getACtDetailById(item.act_id)
                tempObj.actTitle = res.act_title
                tempObj.userAccount = item.user_account
                tempObj.year = item.year
                tempObj.score = item.score
                tempObj.scoreType = item.score_type
                tempObj.scoreTypeStatus = '文体分'

                resList.push(tempObj)
            }
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '文体分已获取',
                data: resList
            }
        } else {
            // 获取分数
            let wentiTotalScore = 0.0
            wentiRes.forEach(item => {
                wentiTotalScore += item.score
            })
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '文体分已获取',
                data: { wentiTotalScore }
            }
        }
    }

    async addLocation (ctx, next) {
        try {
            const { actId, latitude, longitude, address, name } = ctx.request.body
            const getRes = await getActLoaction(actId)
            if (!getRes) {
                const res = await addLocation({ act_id: actId, latitude, longitude, address, name })
                if (res.errorFlag) {
                    console.error('定位失败，数据库新增数据错误', res.message)
                    ctx.status = 500
                } else {
                    ctx.status = 200
                    ctx.body = {
                        hasOk: true,
                        code: 20000,
                        message: '活动已标记定位签到地点',
                        data: {}
                    }
                }
            } else {
                // 定位已经有记录，现已覆盖旧记录
                try {
                    const modifyRes = await modifyLocationByActId({ latitude, longitude, address, name }, actId)
                    if (modifyRes.errorFlag) {
                        console.error('定位失败，数据库错误', modifyRes.message)
                        ctx.status = 500
                    } else {
                        ctx.status = 200
                        ctx.body = {
                            hasOk: true,
                            code: 20000,
                            message: '定位已经有记录，现已覆盖旧记录',
                            data: ''
                        }
                    }
                } catch (error) {
                    ctx.status = 500
                    console.error('数据修改失败', error)
                    return
                }
            }

        } catch (error) {
            console.log(error)
        }
    }

    async isSetLoaction (ctx, next) {
        const { actId } = ctx.request.body
        const getRes = await getActLoaction(actId)
        if (!getRes) {
            ctx.status = 200
            ctx.body = {
                hasOk: false,
                code: 20000,
                message: '举办方未设定签到地点',
                data: {}
            }
            return
        }
        await next()
    }

    // 加分通过审批
    async approvalScoreFile (ctx, next) {
        try {
            const { actId } = ctx.request.body
            const res = await modifyByActId({ score_approval_status: 1 }, actId)
            const scoreRes = await modifyScoreByActId({ score_approval_status: 1 }, actId)
            if (res.errorFlag) {
                console.error('审批失败，数据库错误', res.message)
                ctx.status = 500
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '加分名单审批成功',
                    data: ''
                }
            }
        } catch (error) {
            console.log(error)
        }
    }

    /**
     * 获取某活动的参赛文件列表
     */
    async getEntryList (ctx, next) {
        const { actId } = ctx.query
        const { rows } = await getEntryInfo({ act_id: actId })
        if (rows.length === 0) {
            ctx.status = 200
            ctx.body = {
                hasOk: false,
                code: 20000,
                message: '该比赛未有学生提交参赛文件',
                data: {}
            }
        } else {
            let resList = []
            for (let item of rows) {
                let resObj = {}
                resObj.actId = item.act_id
                resObj.userAccount = item.user_account
                const userRes = await getUserByAccount(item.user_account)
                resObj.userName = userRes.user_name
                resObj.entryPath = item.entry_path
                resObj.entryApprovalStatus = item.entry_approval_status
                if (item.entry_approval_status == 0) {
                    resObj.entryApprovalStatusDetail = '未评分'
                } else if (item.entry_approval_status == 1) {
                    resObj.entryApprovalStatusDetail = '已评分'
                }
                resList.push(resObj)
            }

            resList = resList.sort((a, b) => {
                return a.entryApprovalStatus - b.entryApprovalStatus // 升序排列
            })

            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '文件获取成功',
                data: resList
            }
        }
    }

    /**
     * 比赛老师评分 TODO:
     */
    async marchActBouns (ctx, next) {
        const { actId, userAccount, marchScoreTypeList } = ctx.request.body

        let year = formatDate(new Date()).split(' ')[0]

        let res = {}
        let isSign = false
        let scoreTypeList = JSON.parse(marchScoreTypeList)
        for (let item of scoreTypeList) {
            console.log(item.scoreType)
            switch (item.scoreType) {
                case 0:
                    // 0 为创新分
                    const serachChuangxinRes = await getChuangxinList({ act_id: actId, user_account: userAccount })
                    if (serachChuangxinRes.length === 0) {
                        res = await createChuangxin({ act_id: actId, user_account: userAccount, score: item.score, year, score_approval_status: 3 })
                    } else {
                        isSign = true
                    }
                    break
                case 1:
                    // 1 为学业分
                    const serachXueyeRes = await getXueyeList({ act_id: actId, user_account: userAccount })
                    if (serachXueyeRes.length === 0) {
                        res = await createXueye({ act_id: actId, user_account: userAccount, score: item.score, year, score_approval_status: 3 })
                    } else {
                        isSign = true
                    }
                    break
                case 2:
                    // 2 为思想分
                    const serachSixiangRes = await getSixiangList({ act_id: actId, user_account: userAccount })
                    if (serachSixiangRes.length === 0) {
                        res = await createSixiang({ act_id: actId, user_account: userAccount, score: item.score, year, score_approval_status: 3 })
                    } else {
                        isSign = true
                    }
                    break
                case 3:
                    // 3 为文体分
                    const serachWentiRes = await getWentiList({ act_id: actId, user_account: userAccount })
                    if (serachWentiRes.length === 0) {
                        res = await createWenti({ act_id: actId, user_account: userAccount, score: item.score, year, score_approval_status: 3 })
                    } else {
                        isSign = true
                    }
                    break
            }
        }

        await approvalEntry(1, userAccount, actId)

        if (res.errorFlag) {
            console.error('新增失败，数据库新增数据错误', res.message)
            ctx.status = 500
        } else {
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '评分成功，加分已记录',
                data: {}
            }
        }
    }

    async getActScoreType (ctx, next) {
        const { actId } = ctx.query
        const res = await getActSignScoreListByActId(actId)
        let resList = []
        res.forEach(item => {
            let resObj = {}
            resObj.score = item.score
            resObj.score_type = item.score_type
            resList.push(resObj)
        })
        ctx.body = {
            hasOk: true,
            code: 20000,
            message: '加分类型获取成功',
            data: resList
        }
    }
}



module.exports = new actScoreController()